package com.cll.pmis.common.security;

import com.cll.pmis.common.utils.HttpContextUtil;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpSession;
import java.util.Set;

/**
 * @author chenliangliang
 * @date 2018/6/19
 */
public class SecurityContext {

    public static SysUser currentUser() {
        HttpSession session = HttpContextUtil.getSession();
        return session == null ? null : (SysUser) session.getAttribute("user");
    }

    public static boolean isLogin() {
        return currentUser() != null;
    }

    public static String getUsername() {
        SysUser sysUser = currentUser();
        return sysUser == null ? null : sysUser.getUsername();
    }

    public static Integer getUserId() {
        SysUser sysUser = currentUser();
        return sysUser == null ? null : sysUser.getId();
    }

    public static boolean hasRole(String role) {
        SysUser sysUser = currentUser();
        return sysUser != null && StringUtils.equalsIgnoreCase(sysUser.getRole(), role);
    }

    public static boolean hasPerms(String perms) {
        SysUser sysUser = currentUser();
        return sysUser != null && sysUser.getPerms().contains(perms);
    }

    public static boolean hasAllPrems(String... perms){
        SysUser sysUser = currentUser();
        if (sysUser==null){
            return false;
        }
        Set<String> permsSet = sysUser.getPerms();
        for (String p:perms){
            if (!permsSet.contains(p)){
                return false;
            }
        }
        return true;
    }

    public static void logout(){
        HttpSession session = HttpContextUtil.getSession();
        if (session!=null){
            session.removeAttribute("user");
        }
    }
}
